package com.dongan.controller;


import com.dongan.pojo.MenuRole;
import com.dongan.pojo.Menus;
import com.dongan.service.MenuRoleService;
import com.dongan.service.MenusService;
import com.dongan.utils.ResultResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author longTao
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/menu-role")
@CrossOrigin
public class MenuRoleController {

    @Autowired
    private MenusService menusService;
    @Autowired
    private MenuRoleService menuRoleService;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @CrossOrigin
    @GetMapping(value = "/{id}")
    @PreAuthorize("hasAuthority('/menuDistribution')")
    public ResultResponseUtil queryMenuById(@PathVariable Long id){
        List<Long> longs = menuRoleService.queryMenuBasedOnRoleId(id);
        List<Menus> list = menusService.queryList();
        Map<String,Object> map=new HashMap<>();
        map.put("longs",longs);
        map.put("list",list);
        return new ResultResponseUtil(true,map);
    }

    @CrossOrigin
    @PostMapping(value = "/",produces = {"application/json;charset=utf-8"})
    @PreAuthorize("hasAuthority('/menuDistribution')")
    public ResultResponseUtil menuDistribution(@RequestBody Map<String,Object> map){
        ObjectMapper mapper=new ObjectMapper();
        try {
            Long id = mapper.readValue(map.get("id").toString(), Long.class);
            Long [] arr=mapper.readValue(map.get("arr").toString(), new TypeReference<Long[]>() {});
            menuRoleService.menuDistribution(id,arr);
            return new ResultResponseUtil(true,"菜单分配成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultResponseUtil(false,"菜单分配失败!");
        }
    }

}

